package com.jtdemo.stq.demo.dao.Impl;

import com.jtdemo.stq.demo.dao.PersonDao;
import com.jtdemo.stq.demo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 **@Description: TODO
 **@ClassName: PersonDaoImpl
 **@Author: wjt
 **@Time: 2022/6/24 18:25
 **@Version：1.0
 */
@Repository
public class PersonDaoImpl implements PersonDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;  //注入对象
    @Override
    public List<Person> listPersonByName(int page,String name) {

        List<Map<String, Object>> pesronList = jdbcTemplate.queryForList("select * from `person` where `name`=? limit ?,3",name,(page-1)*3);
        ArrayList<Person> peoples = new ArrayList<>();
        for (int i = 0; i < pesronList.size(); i++) {
            int id = (int) pesronList.get(i).get("ID");
            String username = (String) pesronList.get(i).get("name");
            String sex = (String) pesronList.get(i).get("sex");
            int age= (int) pesronList.get(i).get("age");
            Person person=new Person(id,username,sex,age);
            peoples.add(person);
        }
        return peoples;
    }
    @Override
    public int deletePeopleById(Integer id) {

        return jdbcTemplate.update("delete from `person` where `ID`=?",id);
    }

    @Override
    public int updatePeopleById(Person person) {
        return jdbcTemplate.update("update `person` set `name`=?,`sex`=?,`age`=? where `ID`=?",person.getName(),person.getSex(),person.getAge(),person.getId());
    }

    @Override
    public int addPerson(Person person) {
        return jdbcTemplate.update("insert into `person`(`name`,`sex`,`age`) values (?,?,?)", person
                .getName(),person.getSex(),person.getAge());
    }

    @Override
    public List<Person> listPersonbyCurrentPage(int currentPage) {
        List<Map<String, Object>> pesronList = jdbcTemplate.queryForList("select * from `person` limit ?,3",(currentPage-1)*3);

        ArrayList<Person> peoples = new ArrayList<>();
        for (int i = 0; i < pesronList.size(); i++) {
            int id = (int) pesronList.get(i).get("ID");
            String username = (String) pesronList.get(i).get("name");
            String sex = (String) pesronList.get(i).get("sex");
            int age= (int) pesronList.get(i).get("age");
            Person person=new Person(id,username,sex,age);
            peoples.add(person);
        }

        return peoples;
    }

    @Override
    public int countPerson() {
      return  jdbcTemplate.queryForObject("select count(*) from `person`",Integer.class);
    }
}
